<template>
  <div>
    <el-form :model="addEditSpuParams" label-width="120px">
      <el-form-item label="SPU描述">
        <el-input placeholder="SPU名称" v-model="addEditSpuParams.spuName" />
      </el-form-item>
      <el-form-item label="品牌">
        <el-select v-model="addEditSpuParams.tmId" placeholder="请选择">
          <el-option
            v-for="item in trademarkList"
            :key="item.id"
            :label="item.tmName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input type="textarea" placeholder="SPU描述" v-model="addEditSpuParams.description" />
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          v-model:file-list="fileList"
          :action="uploadUrl"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select placeholder="还有三种未选择">
          <el-option
            v-for="item in formbaseSaleAttr"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-button type="primary">添加销售属性</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="addEditSpuParams.spuSaleAttrList" border>
      <el-table-column type="index" label="序号" width="180" />
      <el-table-column prop="saleAttrName" label="属性值" width="180" />
      <el-table-column label="属性名称列表" width="180">
        <template #default="{ row }">
          <el-tag v-for="attr in row.spuSaleAttrValueList" :key="attr.id" closable>
            {{ attr.saleAttrValueName }}
          </el-tag>

          <el-input
            v-if="row.isEdit"
            ref="InputRef"
            v-model="row.newAttrValueName"
            class="attr-input"
            size="small"
            @keyup.enter="showBtn(row)"
            @blur="showBtn(row)"
          />
          <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(row)">
            + New Tag
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作" />
    </el-table>
    <el-button type="primary">保&emsp;存</el-button>
    <el-button>取&emsp;消</el-button>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, computed, nextTick } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { useCategoryStore } from '@/stores/category'
import { ElMessage, type InputInstance, type UploadProps } from 'element-plus'
import type { IResSpu, IResSpuAttrList, SalesAttributes } from '@/types/spu'
import { storeToRefs } from 'pinia'
import { reqSpuDetails, reqSpuAttributeList, reqSpuImageList } from '@/api/Spu'
import { getAllTrademark } from '@/api/Trademark'
import type { IResTrademarkInfo } from '@/types/trademark'
const categoryStore = useCategoryStore()
const { category3Id } = storeToRefs(categoryStore)

// 创建 input 输入框的引用
const InputRef = ref<InputInstance>()
// 拼接上传的地址
const uploadUrl = import.meta.env.VITE_API_URL + '/admin/product/upload'
// 处理上传成功以后的逻辑
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  addEditSpuParams.value.spuImageList.push({
    imgUrl: response.data,
    imgName: uploadFile.name
  })
}

// 处理上传之前的验证
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('请上传 jpeg 格式的图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小最大是 2MB!')
    return false
  }
  return true
}

const showBtn = (row: IResSpuAttrList) => {
  row.isEdit = false
}
const showInput = (row: IResSpuAttrList) => {
  row.isEdit = true

  nextTick(() => {
    InputRef.value?.focus()
  })
}
const props = defineProps<{
  spuId: number | string
}>()

// 品牌列表数据
const trademarkList = ref<IResTrademarkInfo[]>([])
// 销售属性列表数据
const baseSaleAttrList = ref<SalesAttributes[]>([])

//新增修改所需字段
const addEditSpuParams = ref<IResSpu>({
  category3Id: category3Id.value as number,
  description: '',
  spuImageList: [],
  spuName: '',
  spuSaleAttrList: [],
  tmId: ''
})
//图片列表数据
const fileList = computed({
  get(){
    return addEditSpuParams.value.spuImageList?.map((item) => ({
    url: item.imgUrl || '',
    name: item.imgName
  }))
  },
  set(){
    // 这里面其实不用写任何逻辑
    // 上传组件，它会自己修改 fileList
    // 而我们不希望组件修改
    // 但是如果不写,控制台会有警告
    // 警告可以忽略的。如果不想看到警告，就写 set
    return true
  }

}
//没有被使用过的销售属性
const formbaseSaleAttr = computed(() => {
  const { spuSaleAttrList } = addEditSpuParams.value
  if (!spuSaleAttrList?.length) return baseSaleAttrList.value

  return baseSaleAttrList.value.filter((item1) => {
    // 如果调用 some 以后，返回的是 true，说明属性已经被选择了
    // 已经被选择了，就不需要将当前这一样 filter 过滤
    // 如果调用 some 以后，返回的是 false，说明属性没有被选择
    // 需要将这一项 filter 过滤出来，组成一个新的数组
    return !spuSaleAttrList.some((item2) => item2.baseSaleAttrId === item1.id)
  })
})

//获取品牌销售列表信息
const getTrademarkSpuDetail = async () => {
  const [res1, res2] = await Promise.all([getAllTrademark(), reqSpuAttributeList()])
  if (res1.code === 200 && res2.code === 200) {
    trademarkList.value = res1.data
    baseSaleAttrList.value = res2.data
  }
}

//详情获取图片列表和spu详情信息
const getSpuDetailImage = async () => {
  const spuId = props.spuId as number
  const [res1, res2] = await Promise.all([reqSpuDetails(spuId), reqSpuImageList(spuId)])
  if (res1.code === 200 && res2.code === 200) {
    addEditSpuParams.value = res1.data
    addEditSpuParams.value.spuImageList = res2.data
  }
}

onMounted(() => {
  getTrademarkSpuDetail()
  if (props.spuId) {
    getSpuDetailImage()
  }
})

//#region
/* const fileList = ref<UploadUserFile[]>([
  {
    name: 'food.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
  },
  {
    name: 'food1.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
  }
]) */

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles)
  // 删除以后，提供的形参中能够获取到删除那一项的数据
  // 对 spuImageList 进行遍历，可以使用 findIndex 方法，
  // 判断 imgUrl 和 删除项返回的 Url 是否一致，会返回所以，
  // 使用 splice 进行删除
  const index = addEditSpuParams.value.spuImageList.findIndex(
    (item) => item.imgUrl === uploadFile.url
  )

  addEditSpuParams.value.spuImageList.splice(index, 1)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
//#endregion
</script>

<script lang="ts">
export default {
  name: 'SpuFrom'
}
</script>

<style lang="scss" scoped>
.attr-input {
  width: 80px;
}

.el-tag {
  margin: 5px;
}
</style>
